package com.mz.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import com.mz.base.util.ATTSystem;
import com.mz.entity.SysUsers;
import com.mz.service.LoginService;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String authCode = request.getParameter("authCode");
		String authCodeKey = request.getParameter("authCodeKey");
		
		HttpSession session = request.getSession();
		Object sessionAuthCode = session.getAttribute(authCodeKey);
		
		JSONObject retJson = new JSONObject();
		retJson.put("code", 0);
		if(StringUtils.isEmpty(userName) || userName.length()<6 || userName.length()>20){
			retJson.put("msg", "账号错误");
		}else if(StringUtils.isEmpty(password) || password.length()<6 || password.length()>20){
			retJson.put("msg", "密码错误");
		}else if(sessionAuthCode==null || StringUtils.isEmpty(authCode) || !authCode.equals(sessionAuthCode)){
			retJson.put("msg", "验证码错误");
		}else{
			session.removeAttribute(sessionAuthCode.toString());
			
			SysUsers users = new SysUsers(userName, password, null);
			LoginService loginService = new LoginService();
			retJson = loginService.login(users);
			
			if(retJson.getInt("code") == 1){
				users = (SysUsers) retJson.get("users");
				session.setAttribute(ATTSystem.KEY_SESSION_LOGIN, users);
				retJson.remove("users");
				
				ATTSystem.putMapSessionUserid(session.getId(), users.getUserId());
				
			}
		}
		
		CommonServlet.writer(response, retJson.toString());
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void init() throws ServletException {}
	
	public LoginServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}
}